<template>
  <div class="analysis-container">
    <div class="header">
      <div class="back-btn" @click="router.back()">
        <span class="icon">←</span> 返回
      </div>
      <h1>班级学情分析</h1>
    </div>

    <!-- 总体统计卡片 -->
    <div class="stat-cards">
      <div v-for="stat in stats" :key="stat.id" class="stat-card">
        <div class="stat-icon" :style="{ background: stat.color }">{{ stat.icon }}</div>
        <div class="stat-info">
          <h3>{{ stat.title }}</h3>
          <div class="stat-value">{{ stat.value }}</div>
          <div class="stat-trend" :class="stat.trend">
            {{ stat.trend === 'up' ? '↑' : '↓' }} {{ stat.change }}%
          </div>
        </div>
      </div>
    </div>

    <div class="dashboard">
      <!-- 成绩分布 -->
      <div class="chart-card">
        <h3>成绩分布</h3>
        <v-chart class="chart" :option="gradeDistOption" />
      </div>

      <!-- 知识点掌握情况 -->
      <div class="chart-card">
        <h3>知识点掌握情况</h3>
        <v-chart class="chart" :option="knowledgeOption" />
      </div>

      <!-- 学习进度追踪 -->
      <div class="chart-card">
        <h3>学习进度追踪</h3>
        <v-chart class="chart" :option="progressOption" />
      </div>

      <!-- 作业完成情况 -->
      <div class="chart-card">
        <h3>作业完成情况</h3>
        <v-chart class="chart" :option="homeworkOption" />
      </div>
    </div>

    <!-- 学习建议 -->
    <div class="recommendations">
      <h2>AI 学习建议</h2>
      <div class="recommendation-list">
        <div v-for="(rec, index) in recommendations" 
             :key="index" 
             class="recommendation-card">
          <div class="rec-icon">💡</div>
          <div class="rec-content">
            <h4>{{ rec.title }}</h4>
            <p>{{ rec.content }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import VChart from 'vue-echarts'
import * as echarts from 'echarts/core'
import { GridComponent, TooltipComponent, TitleComponent, LegendComponent } from 'echarts/components'
import { BarChart, LineChart, PieChart, RadarChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { classAPI } from '@/api/admin/college'

// 注册必要的ECharts组件
echarts.use([
  GridComponent, 
  TooltipComponent, 
  TitleComponent, 
  LegendComponent, 
  BarChart, 
  LineChart, 
  PieChart, 
  RadarChart, 
  CanvasRenderer
])

const router = useRouter()
const route = useRoute()

// 从路由参数中获取班级信息
const collegeId = route.params.collegeId
const gradeId = route.params.gradeId
const classId = route.params.classId

// 统计卡片数据
const stats = ref([
  {
    id: 1,
    title: '平均成绩',
    value: '85.6',
    change: 3.2,
    trend: 'up',
    icon: '📊',
    color: '#1890ff'
  },
  {
    id: 2,
    title: '及格率',
    value: '95%',
    change: 2.5,
    trend: 'up',
    icon: '📈',
    color: '#52c41a'
  },
  {
    id: 3,
    title: '作业完成率',
    value: '92%',
    change: 1.8,
    trend: 'up',
    icon: '📝',
    color: '#722ed1'
  },
  {
    id: 4,
    title: '出勤率',
    value: '98%',
    change: 0.5,
    trend: 'down',
    icon: '👥',
    color: '#faad14'
  }
])

// 成绩分布图表配置
const gradeDistOption = ref({
  title: { text: '成绩分布' },
  tooltip: { trigger: 'axis' },
  xAxis: {
    type: 'category',
    data: ['90-100', '80-89', '70-79', '60-69', '<60']
  },
  yAxis: { type: 'value' },
  series: [{
    data: [15, 25, 18, 10, 2],
    type: 'bar',
    barWidth: '40%',
    itemStyle: {
      color: function(params) {
        const colors = ['#52c41a', '#1890ff', '#faad14', '#722ed1', '#f5222d']
        return colors[params.dataIndex]
      }
    }
  }]
})

// 知识点掌握情况
const knowledgeOption = ref({
  radar: {
    indicator: [
      { name: '数据结构', max: 100 },
      { name: '算法分析', max: 100 },
      { name: '编程基础', max: 100 },
      { name: '数据库', max: 100 },
      { name: '计算机网络', max: 100 }
    ]
  },
  series: [{
    type: 'radar',
    data: [{
      value: [85, 78, 90, 82, 75],
      name: '班级平均水平',
      areaStyle: {
        color: 'rgba(24, 144, 255, 0.2)'
      },
      lineStyle: {
        color: '#1890ff'
      }
    }]
  }]
})

// 学习进度追踪
const progressOption = ref({
  xAxis: {
    type: 'category',
    data: ['第1周', '第2周', '第3周', '第4周', '第5周', '第6周']
  },
  yAxis: {
    type: 'value',
    max: 100
  },
  series: [{
    data: [65, 72, 78, 85, 88, 92],
    type: 'line',
    smooth: true,
    lineStyle: {
      color: '#52c41a'
    },
    areaStyle: {
      color: 'rgba(82, 196, 26, 0.2)'
    }
  }]
})

// 作业完成情况
const homeworkOption = ref({
  tooltip: {
    trigger: 'item'
  },
  series: [{
    type: 'pie',
    radius: ['50%', '70%'],
    data: [
      { value: 75, name: '按时完成', itemStyle: { color: '#52c41a' } },
      { value: 15, name: '延迟完成', itemStyle: { color: '#faad14' } },
      { value: 10, name: '未完成', itemStyle: { color: '#f5222d' } }
    ],
    label: {
      formatter: '{b}: {d}%'
    }
  }]
})

// AI学习建议
const recommendations = ref([
  {
    title: '重点关注',
    content: '数据结构中的"树"和"图"章节掌握程度较弱，建议增加相关练习。'
  },
  {
    title: '学习方法优化',
    content: '建议采用"番茄工作法"，每45分钟休息5分钟，提高学习效率。'
  },
  {
    title: '个性化建议',
    content: '根据学生学习曲线，建议在每周一和周四安排重点知识复习。'
  },
  {
    title: '学习资源推荐',
    content: '推荐观看"数据结构与算法"系列视频，配合在线练习平台提高实践能力。'
  }
])

// 获取班级学情分析数据
const fetchClassAnalysis = async () => {
  console.log("正在请求班级数据:", collegeId, gradeId, classId);
  try {
    const response = await classAPI.getClassAnalysis(collegeId, gradeId, classId, 'learning');
    console.log("获取到班级学情数据:", response);
    
    // 更新统计卡片数据
    if (response.stats) {
      // 平均成绩
      if (response.stats.avg_score !== null && response.stats.avg_score !== undefined) {
        stats.value[0].value = response.stats.avg_score.toString();
        stats.value[0].change = parseFloat(response.stats.score_change || '0');
        stats.value[0].trend = parseFloat(response.stats.score_change || '0') >= 0 ? 'up' : 'down';
      } else {
        stats.value[0].value = '暂无数据';
        stats.value[0].change = 0;
        stats.value[0].trend = 'up';
      }
      
      // 及格率
      if (response.stats.pass_rate !== null && response.stats.pass_rate !== undefined) {
        stats.value[1].value = response.stats.pass_rate + '%';
        stats.value[1].change = parseFloat(response.stats.pass_rate_change || '0');
        stats.value[1].trend = parseFloat(response.stats.pass_rate_change || '0') >= 0 ? 'up' : 'down';
      } else {
        stats.value[1].value = '暂无数据';
        stats.value[1].change = 0;
        stats.value[1].trend = 'up';
      }
      
      // 作业完成率
      if (response.stats.homework_completion_rate !== null && response.stats.homework_completion_rate !== undefined) {
        stats.value[2].value = response.stats.homework_completion_rate + '%';
        stats.value[2].change = parseFloat(response.stats.homework_completion_change || '0');
        stats.value[2].trend = parseFloat(response.stats.homework_completion_change || '0') >= 0 ? 'up' : 'down';
      } else {
        stats.value[2].value = '暂无数据';
        stats.value[2].change = 0;
        stats.value[2].trend = 'up';
      }
      
      // 出勤率
      if (response.stats.attendance_rate !== null && response.stats.attendance_rate !== undefined) {
        stats.value[3].value = response.stats.attendance_rate + '%';
        stats.value[3].change = parseFloat(response.stats.attendance_change || '0');
        stats.value[3].trend = parseFloat(response.stats.attendance_change || '0') >= 0 ? 'up' : 'down';
      } else {
        stats.value[3].value = '暂无数据';
        stats.value[3].change = 0;
        stats.value[3].trend = 'up';
      }
    }
    
    // 更新成绩分布图表
    if (response.grade_distribution && response.grade_distribution.values && response.grade_distribution.values.length > 0) {
      gradeDistOption.value.xAxis.data = response.grade_distribution.categories || ['90-100', '80-89', '70-79', '60-69', '<60'];
      gradeDistOption.value.series[0].data = response.grade_distribution.values;
    } else {
      // 设置成空数据但保留图表结构
      gradeDistOption.value.series[0].data = [0, 0, 0, 0, 0];
    }
    
    // 更新知识点掌握情况图表
    if (response.knowledge_mastery && response.knowledge_mastery.areas && response.knowledge_mastery.areas.length > 0 && response.knowledge_mastery.values && response.knowledge_mastery.values.length > 0) {
      knowledgeOption.value.radar.indicator = response.knowledge_mastery.areas.map(area => ({ name: area, max: 100 }));
      knowledgeOption.value.series[0].data = [{
        value: response.knowledge_mastery.values,
        name: '班级平均水平',
        areaStyle: { color: 'rgba(24, 144, 255, 0.2)' },
        lineStyle: { color: '#1890ff' }
      }];
    } else {
      // 保持默认的指标但将值设为0
      knowledgeOption.value.series[0].data = [{
        value: [0, 0, 0, 0, 0],
        name: '暂无数据',
        areaStyle: { color: 'rgba(200, 200, 200, 0.2)' },
        lineStyle: { color: '#cccccc' }
      }];
    }
    
    // 更新学习进度图表
    if (response.learning_progress && response.learning_progress.weeks && response.learning_progress.weeks.length > 0 && response.learning_progress.values && response.learning_progress.values.length > 0) {
      progressOption.value.xAxis.data = response.learning_progress.weeks;
      progressOption.value.series[0].data = response.learning_progress.values;
    } else {
      // 保持默认周数但值设为0
      progressOption.value.series[0].data = [0, 0, 0, 0, 0, 0];
    }
    
    // 更新作业完成情况图表
    if (response.homework_status && 
        ((response.homework_status.ontime && response.homework_status.ontime > 0) || 
         (response.homework_status.late && response.homework_status.late > 0) || 
         (response.homework_status.incomplete && response.homework_status.incomplete > 0))) {
      homeworkOption.value.series[0].data = [
        { value: response.homework_status.ontime || 0, name: '按时完成', itemStyle: { color: '#52c41a' } },
        { value: response.homework_status.late || 0, name: '延迟完成', itemStyle: { color: '#faad14' } },
        { value: response.homework_status.incomplete || 0, name: '未完成', itemStyle: { color: '#f5222d' } }
      ];
    } else {
      // 设置为空数据但保留结构
      homeworkOption.value.series[0].data = [
        { value: 0, name: '按时完成', itemStyle: { color: '#eeeeee' } },
        { value: 0, name: '延迟完成', itemStyle: { color: '#eeeeee' } },
        { value: 1, name: '暂无数据', itemStyle: { color: '#cccccc' } }
      ];
    }
    
    // 更新学习建议
    if (response.recommendations && response.recommendations.length > 0) {
      recommendations.value = response.recommendations;
    } else {
      // 设置空数据
      recommendations.value = [{
        title: '暂无建议',
        content: '当前暂无足够的学习数据，无法生成学习建议。'
      }];
    }
    
  } catch (error) {
    console.error("获取班级学习情况失败:", error);
    // 在发生错误时使用默认空数据
    stats.value.forEach(stat => {
      stat.value = '加载失败';
      stat.change = 0;
    });
    
    // 使用空图表数据但保留结构
    gradeDistOption.value.series[0].data = [0, 0, 0, 0, 0];
    
    knowledgeOption.value.series[0].data = [{
      value: [0, 0, 0, 0, 0],
      name: '加载失败',
      areaStyle: { color: 'rgba(200, 200, 200, 0.2)' },
      lineStyle: { color: '#cccccc' }
    }];
    
    progressOption.value.series[0].data = [0, 0, 0, 0, 0, 0];
    
    homeworkOption.value.series[0].data = [
      { value: 0, name: '按时完成', itemStyle: { color: '#eeeeee' } },
      { value: 0, name: '延迟完成', itemStyle: { color: '#eeeeee' } },
      { value: 1, name: '加载失败', itemStyle: { color: '#cccccc' } }
    ];
    
    recommendations.value = [{
      title: '数据加载失败',
      content: '无法获取学习数据，请检查网络连接或稍后再试。'
    }];
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchClassAnalysis();
});
</script>

<style scoped>
.analysis-container {
  padding: 30px;
}

.header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
}

.back-btn {
  padding: 10px 20px;
  background: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.dashboard {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chart {
  height: 300px;
}

.recommendations {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.recommendation-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.recommendation-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  gap: 15px;
}

.trend.up { color: #52c41a; }
.trend.down { color: #f5222d; }
</style> 